package com.lagou.edu.ioc;

import com.lagou.edu.annotation.Autowired;
import com.lagou.edu.annotation.Component;
import com.lagou.edu.transaction.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Kirito
 * @description:
 * @date 2020/04/04
 */
@Component
public class ProxyFactory {

    @Autowired
    private TransactionManager transactionManager;

    /*public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }*/

    /*private static ProxyFactory proxyFactory = new ProxyFactory();

    private ProxyFactory() {
    }

    public static ProxyFactory getInstance() {
        return proxyFactory;
    }*/

    public Object createJdkProxy(Object target) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                Object result;
                try {
                    transactionManager.open();
                    result = method.invoke(target, objects);

                    transactionManager.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    transactionManager.rollback();
                    throw new RuntimeException(e);
                }
                return result;
            }
        });
    }

    public Object createCglibProxy(Object target) {
        return Enhancer.create(target.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                transactionManager.open();
                Object result;
                try {
                    result = method.invoke(target, objects);

                    transactionManager.commit();
                } catch (Exception e) {
                    transactionManager.rollback();
                    throw new RuntimeException(e);
                }
                return result;
            }
        });
    }
}
